package org.dubnation.base.excel.upload.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.dubnation.base.excel.download.service.IDownloadService;
import org.dubnation.base.excel.download.vo.UploadErrorMsgVO;
import org.dubnation.base.excel.upload.dto.EmployeeDTO;
import org.dubnation.base.excel.upload.service.IUploadService;
import org.dubnation.base.excel.upload.util.ExcelVerifyHandler;
import org.dubnation.base.excel.upload.util.HttpStatusEnum;
import org.dubnation.base.exception.FileException;
import org.dubnation.org.domain.Department;
import org.dubnation.org.domain.Employee;
import org.dubnation.org.mapper.DepartmentMapper;
import org.dubnation.org.mapper.EmployeeMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class UploadServiceImpl implements IUploadService {

    @Autowired
    private ExcelVerifyHandler excelVerifyHandler;

    @Autowired(required = false)
    private DepartmentMapper departmentMapper;

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Autowired
    private IDownloadService downloadService;

    /**
     * 上传文件
     * @param file
     */
    @Override
    public Object upload(MultipartFile file) {
        StringBuffer verifyResult1 = new StringBuffer(); //用于返回错误信息
        if (Objects.isNull(file) || file.getSize() == 0){
            return verifyResult1.append(HttpStatusEnum.BAD_REQUEST.getMessage()).toString();
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        //开启校验
        params.setNeedVerfiy(true);
        //自定义校验器
        params.setVerifyHandler(excelVerifyHandler);
        InputStream inputStream = null;
        ExcelImportResult<EmployeeDTO> excelImportResult = null;
        try {
            inputStream = file.getInputStream();
            //根据流导入
            excelImportResult = ExcelImportUtil.importExcelMore(inputStream, EmployeeDTO.class, params);
            //是否校验失败
            List<String> verifyResults = new ArrayList<>(); //存储错误数据信息
            StringBuilder verifyResult2 = null;
            if (excelImportResult.isVerfiyFail()) {
                List<UploadErrorMsgVO> errorMsgList = new ArrayList<>();
                for (EmployeeDTO employeeDTO : excelImportResult.getFailList()) {
                    verifyResult2 = new StringBuilder();
                    verifyResult2.append("错误行:" + employeeDTO.getRowNum() + ", 错误信息:" + employeeDTO.getErrorMsg());
                    verifyResults.add(verifyResult2.toString());
                    //将错误信息导出excel
                    UploadErrorMsgVO errorMsgVO = new UploadErrorMsgVO();
                    errorMsgVO.setRowNum(employeeDTO.getRowNum());
                    errorMsgVO.setErrorMsg(employeeDTO.getErrorMsg());
                    errorMsgList.add(errorMsgVO);
                }
                downloadService.exportErrorMsg(errorMsgList);
            }
            //校验成功
            List<EmployeeDTO> employeeDTOList = excelImportResult.getList();
            //入库
            employeeDTOList.forEach(employeeDTO -> {
                Employee employee = new Employee();
                BeanUtils.copyProperties(employeeDTO, employee);
                employee.setSex(Integer.valueOf(employeeDTO.getSex()));
                employee.setState(Integer.valueOf(employeeDTO.getState()));
                Department department = departmentMapper.queryByName(employeeDTO.getDepartmentDTO().getName());
                employee.setDepartment(department);
                employeeMapper.insert(employee);
            });
            return verifyResults; //返回导入数据校验结果
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExcelImportException(e.getMessage());
        }finally {
            try {
                //关流
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
